﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading.Tasks;
using BZ.Logger;
using NDK.Module.Model;

namespace NDK.LocalUtils.Yield
{
    /// <summary>
    /// SQLite数据库产量统计操作类
    /// </summary>
    public class Yield
    {
        private static object syncObj = new object();

        private static Yield _instance;

        /// <summary>
        /// 交接小时
        /// </summary>
        private string handOverHour = "8";

        /// <summary>
        /// 交接分钟
        /// </summary>
        private string handOverMinute = "30";

        /// <summary>
        /// 当前班次产量字典，时间段信息和每小时的产能组成的字典(对外开放产量统计的接口)
        /// </summary>
        private Dictionary<string, HourCapacity> dicCurHourCapacity = new Dictionary<string, HourCapacity>();

        /// <summary>
        /// 白班工作时间段小时和分钟表达式(07:00-08:00表达方式)
        /// </summary>
        private List<string> dayTimeSlotStrs = new List<string>();

        /// <summary>
        /// 夜班工作时间段小时和分钟表达式(19:00-20:00表达方式)
        /// </summary>
        private List<string> nightTimeSlotStrs = new List<string>();

        /// <summary>
        /// 单例模式
        /// </summary>
        public static Yield Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (syncObj)
                    {
                        if (_instance == null)
                        {
                            _instance = new Yield();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 交接小时
        /// </summary>
        public string HandOverHour
        {
            get
            {
                return handOverHour;
            }
            set
            {
                handOverHour = value;
            }
        }

        /// <summary>
        /// 交接分钟
        /// </summary>
        public string HandOverMinute
        {
            get
            {
                return handOverMinute;
            }
            set
            {
                handOverMinute = value;
            }
        }

        /// <summary>
        /// 当前班次产量字典，时间段信息和每小时的产能组成的字典(对外开放产量统计的接口)
        /// </summary>
        public Dictionary<string, HourCapacity> CurHourCapacity
        {
            get
            {
                return dicCurHourCapacity;
            }
            set
            {
                dicCurHourCapacity = value;
            }
        }

        /// <summary>
        /// 小时产能变化事件
        /// </summary>
        public event EventHandler<Dictionary<string, HourCapacity>> HourCapacityChangedEvent;

        /// <summary>
        /// 班次产能变化事件
        /// </summary>
        public event EventHandler<Dictionary<string, ClassesCapacity>> ClassesCapacityChangedEvent;

        /// <summary>
        /// 搜索小时产能统计事件
        /// </summary>
        public event EventHandler<Dictionary<string, HourCapacity>> SearchHourCapacityEvent;

        /// <summary>
        /// 搜索班次产能统计事件
        /// </summary>
        public event EventHandler<Dictionary<string, ClassesCapacity>> SearchClassesCapacityEvent;

        /// <summary>
        /// 读取产量统计信息
        /// </summary>
        /// <returns>true,读取成功|false,读取失败</returns>
        public bool ReadYield()
        {
            try
            {
                string sqlstr = string.Empty;
                string tableName = "HandOverTime";
                List<string> lsTable = SQLiteHandle.GetSQLTable();
                if (!lsTable.Contains(tableName))
                {
                    sqlstr = string.Format("CREATE TABLE IF NOT EXISTS {0}({1}   NVARCHAR PRIMARY KEY  NOT NULL ,", tableName, "HandHour") + string.Format("{0} NVARCHAR NOT NULL)", "HandMinutes");
                    if (!SQLiteHandle.ExecuteNonQuery(sqlstr))
                    {
                        return false;
                    }
                    sqlstr = $"INSERT INTO {tableName} VALUES('07','00')";
                    if (!SQLiteHandle.ExecuteNonQuery(sqlstr))
                    {
                        return false;
                    }
                    sqlstr = $"SELECT * FROM {tableName} LIMIT 1";
                    DbDataReader dr3 = SQLiteHandle.ExecuteReader(sqlstr);
                    while (dr3.Read())
                    {
                        handOverHour = dr3.GetString(0);
                        handOverMinute = dr3.GetString(1);
                    }
                }
                else
                {
                    sqlstr = $"SELECT * FROM {tableName}";
                    DbDataReader dr2 = SQLiteHandle.ExecuteReader(sqlstr);
                    while (dr2.Read())
                    {
                        handOverHour = dr2.GetString(0);
                        handOverMinute = dr2.GetString(1);
                    }
                }
                string startTm = $"{handOverHour}:{handOverMinute}";
                List<string> ls1 = new List<string>();
                List<string> ls3 = new List<string>();
                string tm = string.Empty;
                for (int k = 0; k < 24; k++)
                {
                    sqlstr = $"select time('{startTm}', '+{k + 1} hours')";
                    DbDataReader dr = SQLiteHandle.ExecuteReader(sqlstr);
                    while (dr.Read())
                    {
                        tm = dr.GetString(0);
                    }
                    if (k < 12)
                    {
                        ls1.Add(tm);
                    }
                    else
                    {
                        ls3.Add(tm);
                    }
                }
                sqlstr = $"select time('{startTm}')";
                DbDataReader dd = SQLiteHandle.ExecuteReader(sqlstr);
                while (dd.Read())
                {
                    tm = dd.GetString(0);
                }
                ls1.Insert(0, tm.ToString());
                sqlstr = $"select time('{ls3[0]}', '-1 hours')";
                dd = SQLiteHandle.ExecuteReader(sqlstr);
                while (dd.Read())
                {
                    tm = dd.GetString(0);
                }
                ls3.Insert(0, tm.ToString());
                List<string> ls2 = new List<string>();
                List<string> ls4 = new List<string>();
                ls2.Clear();
                ls4.Clear();
                ls1.ForEach(delegate (string x)
                {
                    ls2.Add(x.Substring(0, x.LastIndexOf(":")));
                });
                ls3.ForEach(delegate (string x)
                {
                    ls4.Add(x.Substring(0, x.LastIndexOf(":")));
                });
                dayTimeSlotStrs.Clear();
                nightTimeSlotStrs.Clear();
                for (int j = 0; j < ls2.Count && j != ls2.Count - 1; j++)
                {
                    dayTimeSlotStrs.Add($"{ls2[j]}-{ls2[j + 1]}");
                }
                for (int i = 0; i < ls4.Count && i != ls4.Count - 1; i++)
                {
                    nightTimeSlotStrs.Add($"{ls4[i]}-{ls4[i + 1]}");
                }
                tableName = "Capacity";
                if (!lsTable.Contains(tableName))
                {
                    sqlstr = string.Format("CREATE TABLE IF NOT EXISTS {0}({1}   NVARCHAR PRIMARY KEY  NOT NULL ,", tableName, "UpdateTime") + string.Format("{0} NVARCHAR NOT NULL)", "Result");
                    if (!SQLiteHandle.ExecuteNonQuery(sqlstr))
                    {
                        return false;
                    }
                }
                string classes = GetCurClasses();
                if (!UpdateCurClassesYield(classes))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"ReadYield --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 获取当前的班次
        /// </summary>
        /// <returns>Day,白班|Night,夜班</returns>
        public string GetCurClasses()
        {
            string curClasses = string.Empty;
            try
            {
                DateTime dt = Convert.ToDateTime($"{handOverHour}:{handOverMinute}");
                string date = string.Empty;
                date = ((!(DateTime.Now >= dt)) ? dt.AddDays(-1.0).ToString("yyyy-MM-dd ") : dt.ToString("yyyy-MM-dd "));
                List<WorkTimeSlot> dayslots = new List<WorkTimeSlot>();
                List<WorkTimeSlot> nightslots = new List<WorkTimeSlot>();
                for (int i = 0; i < 24; i++)
                {
                    string sr = string.Format("{0}{1}{2}{3}{4} ", date, handOverHour, ":", handOverMinute, ":00");
                    DateTime starttm = Convert.ToDateTime(sr).AddHours(i);
                    DateTime endtm = Convert.ToDateTime(sr).AddHours(i + 1);
                    WorkTimeSlot workTimeSlot = new WorkTimeSlot();
                    workTimeSlot.StartTime = starttm;
                    workTimeSlot.EndTime = endtm;
                    if (i < 12)
                    {
                        dayslots.Add(workTimeSlot);
                    }
                    else
                    {
                        nightslots.Add(workTimeSlot);
                    }
                }
                DateTime curdt = DateTime.Now;
                if (dayslots.FindIndex((WorkTimeSlot x) => x.StartTime <= curdt && x.EndTime > curdt) != -1)
                {
                    curClasses = "Day";
                }
                else if (nightslots.FindIndex((WorkTimeSlot x) => x.StartTime <= curdt && x.EndTime > curdt) != -1)
                {
                    curClasses = "Night";
                }
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"GetCurClasses -->  " + ex.ToString(), LogType.Error);
            }
            return curClasses;
        }

        /// <summary>
        /// 更新当前班次的产量统计信息
        /// </summary>
        /// <param name="classes">当前班次,Day(白班)|Night(夜班)</param>
        /// <returns>true,更新成功|false,更新失败</returns>
        private bool UpdateCurClassesYield(string classes)
        {
            try
            {
                Dictionary<string, HourCapacity> dicDayCapacity = new Dictionary<string, HourCapacity>();
                Dictionary<string, HourCapacity> dicNightCapacity = new Dictionary<string, HourCapacity>();
                List<WorkTimeSlot> dayWorkTimeSlots = new List<WorkTimeSlot>();
                List<WorkTimeSlot> nightWorkTimeSlots = new List<WorkTimeSlot>();
                string sqlstr = string.Empty;
                DateTime dt = Convert.ToDateTime($"{handOverHour}:{handOverMinute}");
                string date = string.Empty;
                date = ((!(DateTime.Now >= dt)) ? dt.AddDays(-1.0).ToString("yyyy-MM-dd ") : dt.ToString("yyyy-MM-dd "));
                dayWorkTimeSlots.Clear();
                nightWorkTimeSlots.Clear();
                for (int j = 0; j < 24; j++)
                {
                    string sr = string.Format("{0}{1}{2}{3}{4} ", date, handOverHour, ":", handOverMinute, ":00");
                    DateTime starttm = Convert.ToDateTime(sr).AddHours(j);
                    DateTime endtm = Convert.ToDateTime(sr).AddHours(j + 1);
                    WorkTimeSlot workTimeSlot = new WorkTimeSlot();
                    workTimeSlot.StartTime = starttm;
                    workTimeSlot.EndTime = endtm;
                    if (j < 12)
                    {
                        dayWorkTimeSlots.Add(workTimeSlot);
                    }
                    else
                    {
                        nightWorkTimeSlots.Add(workTimeSlot);
                    }
                }
                if (!(classes == "Day"))
                {
                    if (classes == "Night")
                    {
                        dicNightCapacity.Clear();
                        for (int i = 0; i < nightWorkTimeSlots.Count; i++)
                        {
                            HourCapacity hourCapacity = new HourCapacity();
                            DbDataReader dataReader = null;
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[i].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[i].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                hourCapacity.OkCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[i].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[i].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                hourCapacity.NgCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", nightWorkTimeSlots[i].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", nightWorkTimeSlots[i].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                hourCapacity.TotalCount = dataReader.GetInt32(0);
                            }
                            dicNightCapacity.Add(nightTimeSlotStrs[i], hourCapacity);
                        }
                        if (this.HourCapacityChangedEvent != null)
                        {
                            this.HourCapacityChangedEvent(new object(), dicNightCapacity);
                        }
                        dicCurHourCapacity = new Dictionary<string, HourCapacity>(dicNightCapacity);
                    }
                }
                else
                {
                    dicDayCapacity.Clear();
                    for (int k = 0; k < dayWorkTimeSlots.Count; k++)
                    {
                        HourCapacity hourCapacity2 = new HourCapacity();
                        DbDataReader dataReader2 = null;
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[k].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[k].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                        dataReader2 = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader2.Read())
                        {
                            hourCapacity2.OkCount = dataReader2.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[k].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[k].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                        dataReader2 = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader2.Read())
                        {
                            hourCapacity2.NgCount = dataReader2.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", dayWorkTimeSlots[k].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", dayWorkTimeSlots[k].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        dataReader2 = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader2.Read())
                        {
                            hourCapacity2.TotalCount = dataReader2.GetInt32(0);
                        }
                        dicDayCapacity.Add(dayTimeSlotStrs[k], hourCapacity2);
                    }
                    if (this.HourCapacityChangedEvent != null)
                    {
                        this.HourCapacityChangedEvent(new object(), dicDayCapacity);
                    }
                    dicCurHourCapacity = new Dictionary<string, HourCapacity>(dicDayCapacity);
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"UpdateCurClassesYield --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 更新自定义日期的产量统计
        /// </summary>
        /// <param name="dt">自定义日期</param>
        /// <param name="classes">自定义班次,Day|Night</param>
        /// <returns>true,更新成功|false,更新失败</returns>
        private bool UpdateCurClassesYield(DateTime dt, string classes)
        {
            try
            {
                Dictionary<string, HourCapacity> dicDayCapacity = new Dictionary<string, HourCapacity>();
                Dictionary<string, HourCapacity> dicNightCapacity = new Dictionary<string, HourCapacity>();
                List<WorkTimeSlot> dayWorkTimeSlots = new List<WorkTimeSlot>();
                List<WorkTimeSlot> nightWorkTimeSlots = new List<WorkTimeSlot>();
                string sqlstr = string.Empty;
                string date = dt.ToString("yyyy-MM-dd ");
                dayWorkTimeSlots.Clear();
                nightWorkTimeSlots.Clear();
                for (int i = 0; i < 24; i++)
                {
                    string sr = string.Format("{0}{1}{2}{3}{4} ", date, handOverHour, ":", handOverMinute, ":00");
                    DateTime starttm = Convert.ToDateTime(sr).AddHours(i);
                    DateTime endtm = Convert.ToDateTime(sr).AddHours(i + 1);
                    WorkTimeSlot workTimeSlot = new WorkTimeSlot();
                    workTimeSlot.StartTime = starttm;
                    workTimeSlot.EndTime = endtm;
                    if (i < 12)
                    {
                        dayWorkTimeSlots.Add(workTimeSlot);
                    }
                    else
                    {
                        nightWorkTimeSlots.Add(workTimeSlot);
                    }
                }
                if (!(classes == "Day"))
                {
                    if (classes == "Night")
                    {
                        dicNightCapacity.Clear();
                        for (int j = 0; j < nightWorkTimeSlots.Count; j++)
                        {
                            HourCapacity hourCapacity = new HourCapacity();
                            DbDataReader dataReader = null;
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[j].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[j].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                hourCapacity.OkCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[j].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[j].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                hourCapacity.NgCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", nightWorkTimeSlots[j].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", nightWorkTimeSlots[j].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                hourCapacity.TotalCount = dataReader.GetInt32(0);
                            }
                            dicNightCapacity.Add(nightTimeSlotStrs[j], hourCapacity);
                        }
                        if (this.SearchHourCapacityEvent != null)
                        {
                            this.SearchHourCapacityEvent(new object(), dicNightCapacity);
                        }
                    }
                }
                else
                {
                    dicDayCapacity.Clear();
                    for (int k = 0; k < dayWorkTimeSlots.Count; k++)
                    {
                        HourCapacity hourCapacity2 = new HourCapacity();
                        DbDataReader dataReader2 = null;
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[k].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[k].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                        dataReader2 = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader2.Read())
                        {
                            hourCapacity2.OkCount = dataReader2.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[k].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[k].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                        dataReader2 = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader2.Read())
                        {
                            hourCapacity2.NgCount = dataReader2.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", dayWorkTimeSlots[k].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", dayWorkTimeSlots[k].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        dataReader2 = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader2.Read())
                        {
                            hourCapacity2.TotalCount = dataReader2.GetInt32(0);
                        }
                        dicDayCapacity.Add(dayTimeSlotStrs[k], hourCapacity2);
                    }
                    if (this.SearchHourCapacityEvent != null)
                    {
                        this.SearchHourCapacityEvent(new object(), dicDayCapacity);
                    }
                }
                string date2 = DateTime.Now.AddDays(-180.0).ToString("yyyy-MM-dd");
                string date3 = string.Empty;
                sqlstr = "SELECT date(Min(UpdateTime),'-180 day') FROM Capacity";
                DbDataReader reader = SQLiteHandle.ExecuteReader(sqlstr);
                while (reader.Read())
                {
                    date3 = reader.GetString(0);
                }
                if (Convert.ToDateTime(date2) >= Convert.ToDateTime(date3))
                {
                    sqlstr = "DELETE FROM Capacity WHERE  UpdateTime < (SELECT date(Max(UpdateTime),'-180 day') FROM Capacity)";
                    if (!SQLiteHandle.ExecuteNonQuery(sqlstr))
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"UpdateCurClassesYield --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 更新最近一周的产量统计信息
        /// </summary>
        /// <param name="classes">当前班次,Day(白班)|Night(夜班)</param>
        /// <returns></returns>
        private bool UpdateWeekClassesYield(string classes)
        {
            try
            {
                Dictionary<string, ClassesCapacity> dicDayWeekCapacity = new Dictionary<string, ClassesCapacity>();
                Dictionary<string, ClassesCapacity> dicNightWeekCapacity = new Dictionary<string, ClassesCapacity>();
                List<WorkTimeSlot> dayWorkTimeSlots = new List<WorkTimeSlot>();
                List<WorkTimeSlot> nightWorkTimeSlots = new List<WorkTimeSlot>();
                string sqlstr = string.Empty;
                for (int j = 7; j > 0; j--)
                {
                    DateTime dt = Convert.ToDateTime($"{handOverHour}:{handOverMinute}");
                    string date = string.Empty;
                    date = ((!(DateTime.Now >= dt)) ? dt.AddDays(-(j - 1)).AddDays(-1.0).ToString("yyyy-MM-dd ") : dt.AddDays(-(j - 1)).ToString("yyyy-MM-dd "));
                    dayWorkTimeSlots.Clear();
                    nightWorkTimeSlots.Clear();
                    for (int i = 0; i < 24; i++)
                    {
                        string sr = string.Format("{0}{1}{2}{3}{4} ", date, handOverHour, ":", handOverMinute, ":00");
                        DateTime starttm = Convert.ToDateTime(sr).AddHours(i);
                        DateTime endtm = Convert.ToDateTime(sr).AddHours(i + 1);
                        WorkTimeSlot workTimeSlot = new WorkTimeSlot();
                        workTimeSlot.StartTime = starttm;
                        workTimeSlot.EndTime = endtm;
                        if (i < 12)
                        {
                            dayWorkTimeSlots.Add(workTimeSlot);
                        }
                        else
                        {
                            nightWorkTimeSlots.Add(workTimeSlot);
                        }
                    }
                    DbDataReader dataReader = null;
                    if (!(classes == "Day"))
                    {
                        if (classes == "Night")
                        {
                            ClassesCapacity capacity2 = new ClassesCapacity();
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                capacity2.OkCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                capacity2.NgCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", nightWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", nightWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                capacity2.TotalCount = dataReader.GetInt32(0);
                            }
                            dicNightWeekCapacity.Add(date, capacity2);
                        }
                    }
                    else
                    {
                        ClassesCapacity capacity = new ClassesCapacity();
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                        dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader.Read())
                        {
                            capacity.OkCount = dataReader.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                        dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader.Read())
                        {
                            capacity.NgCount = dataReader.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", dayWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", dayWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader.Read())
                        {
                            capacity.TotalCount = dataReader.GetInt32(0);
                        }
                        dicDayWeekCapacity.Add(date, capacity);
                    }
                }
                if (classes == "Day")
                {
                    if (this.ClassesCapacityChangedEvent != null)
                    {
                        this.ClassesCapacityChangedEvent(new object(), dicDayWeekCapacity);
                    }
                }
                else if (this.ClassesCapacityChangedEvent != null)
                {
                    this.ClassesCapacityChangedEvent(new object(), dicNightWeekCapacity);
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"UpdateWeekClassesYield --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 按照日期更新近一周的产量统计
        /// </summary>
        /// <param name="dt">自定义日期</param>
        /// <param name="classes">自定义班次,Day|Night</param>
        /// <returns>true,更新成功|false,更新失败</returns>
        private bool UpdateWeekClassesYield(DateTime dt, string classes)
        {
            try
            {
                Dictionary<string, ClassesCapacity> dicDayWeekCapacity = new Dictionary<string, ClassesCapacity>();
                Dictionary<string, ClassesCapacity> dicNightWeekCapacity = new Dictionary<string, ClassesCapacity>();
                List<WorkTimeSlot> dayWorkTimeSlots = new List<WorkTimeSlot>();
                List<WorkTimeSlot> nightWorkTimeSlots = new List<WorkTimeSlot>();
                string sqlstr = string.Empty;
                for (int j = 7; j > 0; j--)
                {
                    string date = string.Empty;
                    date = dt.AddDays(-(j - 1)).ToString("yyyy-MM-dd ");
                    dayWorkTimeSlots.Clear();
                    nightWorkTimeSlots.Clear();
                    for (int i = 0; i < 24; i++)
                    {
                        string sr = string.Format("{0}{1}{2}{3}{4} ", date, handOverHour, ":", handOverMinute, ":00");
                        DateTime starttm = Convert.ToDateTime(sr).AddHours(i);
                        DateTime endtm = Convert.ToDateTime(sr).AddHours(i + 1);
                        WorkTimeSlot workTimeSlot = new WorkTimeSlot();
                        workTimeSlot.StartTime = starttm;
                        workTimeSlot.EndTime = endtm;
                        if (i < 12)
                        {
                            dayWorkTimeSlots.Add(workTimeSlot);
                        }
                        else
                        {
                            nightWorkTimeSlots.Add(workTimeSlot);
                        }
                    }
                    DbDataReader dataReader = null;
                    if (!(classes == "Day"))
                    {
                        if (classes == "Night")
                        {
                            ClassesCapacity capacity2 = new ClassesCapacity();
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                capacity2.OkCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", nightWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", nightWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                capacity2.NgCount = dataReader.GetInt32(0);
                            }
                            sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", nightWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", nightWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                            while (dataReader.Read())
                            {
                                capacity2.TotalCount = dataReader.GetInt32(0);
                            }
                            dicNightWeekCapacity.Add(date, capacity2);
                        }
                    }
                    else
                    {
                        ClassesCapacity capacity = new ClassesCapacity();
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='OK'";
                        dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader.Read())
                        {
                            capacity.OkCount = dataReader.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}' ", dayWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format("AND '{0}' ", dayWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss")) + "AND Result='NG'";
                        dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader.Read())
                        {
                            capacity.NgCount = dataReader.GetInt32(0);
                        }
                        sqlstr = "SELECT COUNT(Result) FROM Capacity WHERE UpdateTime BETWEEN " + string.Format("'{0}'", dayWorkTimeSlots[0].StartTime.ToString("yyyy-MM-dd HH:mm:ss")) + string.Format(" AND '{0}'", dayWorkTimeSlots[11].EndTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        dataReader = SQLiteHandle.ExecuteReader(sqlstr);
                        while (dataReader.Read())
                        {
                            capacity.TotalCount = dataReader.GetInt32(0);
                        }
                        dicDayWeekCapacity.Add(date, capacity);
                    }
                }
                if (classes == "Day")
                {
                    if (this.SearchClassesCapacityEvent != null)
                    {
                        this.SearchClassesCapacityEvent(new object(), dicDayWeekCapacity);
                    }
                }
                else if (this.SearchClassesCapacityEvent != null)
                {
                    this.SearchClassesCapacityEvent(new object(), dicNightWeekCapacity);
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"UpdateWeekClassesYield -->" + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 更新产能统计
        /// </summary>
        /// <param name="ret">true,OK产品|false,NG产品</param>
        /// <returns>true,更新成功|false,更新失败</returns>
        public bool UpdateYield(bool ret)
        {
            try
            {
                string tableName = "Capacity";
                string sqlstr = string.Empty;
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                string retstr = (ret ? "OK" : "NG");
                sqlstr = $"INSERT INTO {tableName} VALUES ('{time}','{retstr}')";
                if (!SQLiteHandle.ExecuteNonQuery(sqlstr))
                {
                    return false;
                }
                //if (ShowClassesYield())
                //{
                //    return true;
                //}
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"UpdateYield --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 设置交接时间
        /// </summary>
        /// <param name="hour">交接小时,"HH"表达方式</param>
        /// <param name="minute">交接分钟,"mm"表达方式</param>
        /// <returns>true,设置成功|false,设置失败</returns>
        public bool SetHandOverTime(string hour, string minute)
        {
            try
            {
                string sqlstr = $"UPDATE HandOverTime set HandHour ='{hour}',HandMinutes = '{minute}'";
                if (!SQLiteHandle.ExecuteNonQuery(sqlstr))
                {
                    return false;
                }
                if (!ReadYield())
                {
                    return false;
                }
                if (ShowClassesYield())
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"SetHandOverTime --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 显示当前班次的产量统计
        /// </summary>
        /// <returns>true,显示成功|false,显示失败</returns>
        public bool ShowClassesYield()
        {
            try
            {
                string classes = GetCurClasses();
                if (!UpdateCurClassesYield(classes))
                {
                    return false;
                }
                if (!UpdateWeekClassesYield(classes))
                {
                    return false;
                }
                Task.Factory.StartNew(delegate
                {
                });
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"ShowClassesYield --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }

        /// <summary>
        /// 搜索班次的产量统计
        /// </summary>
        /// <param name="dt">搜索日期</param>
        /// <param name="classes">当前班次,Day|Night</param>
        /// <returns>true,搜索成功|false,搜索失败</returns>
        public bool SearchClassesYield(DateTime dt, string classes)
        {
            try
            {
                if (!UpdateCurClassesYield(dt, classes))
                {
                    return false;
                }
                if (!UpdateWeekClassesYield(dt, classes))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log($"SearchClassesYield --> " + ex.ToString(), LogType.Error);
                return false;
            }
        }
    }
}
